import React, { useState, useCallback } from 'react';

// 模拟登录 API
const fakeLoginApi = (username, password) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      if (username === 'admin' && password === '123456') {
        resolve({ isLoggedIn: true, message: 'Login successful' });
      } else {
        resolve({ isLoggedIn: false, message: 'Invalid credentials' });
      }
    }, 1000);
  });
};

// 自定义 Hook: useActionState
const useActionState = (initialState) => {
  const [state, setState] = useState(initialState);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  // 执行操作的函数
  const executeAction = useCallback(
    (actionFn) => {
      setLoading(true);
      setError(null);
      return actionFn()
        .then((result) => {
          setState(result);
          return result;
        })
        .catch((err) => {
          setError(err.message || 'An unknown error occurred');
          throw err;
        })
        .finally(() => {
          setLoading(false);
        });
    },
    []
  );

  return { state, loading, error, executeAction };
};

// 登录表单组件
const LoginForm = () => {
  // 使用自定义 Hook
  const { state, loading, error, executeAction } = useActionState({
    isLoggedIn: false,
    message: '',
  });

  // 处理登录逻辑
  const handleLogin = async (username, password) => {
    await executeAction(() => fakeLoginApi(username, password));
  };

  return (
    <div>
      <h2>Login</h2>
      <form
        onSubmit={(e) => {
          e.preventDefault();
          const username = document.getElementById('username').value;
          const password = document.getElementById('password').value;
          handleLogin(username, password);
        }}
      >
        <div>
          <label>
            Username:
            <input type="text" id="username" />
          </label>
        </div>
        <div>
          <label>
            Password:
            <input type="password" id="password" />
          </label>
        </div>
        <button type="submit" disabled={loading}>
          {loading ? 'Logging in...' : 'Login'}
        </button>
      </form>
      {error && <p style={{ color: 'red' }}>{error}</p>}
      {state.isLoggedIn && <p style={{ color: 'green' }}>{state.message}</p>}
    </div>
  );
};

export default LoginForm;